import 'dart:async';
import 'package:flutter_get_x/RouteConfig.dart';
import 'package:flutter_get_x/entity/user.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'state.dart';

class EntranceLogic extends GetxController {
  final state = EntranceState();

  Timer _timer;
  final step = 50;
  double stepPrecent;
  User _user;

  @override
  onInit() {
    stepPrecent = step.toDouble() / state.COUNT;
    _getUserInfo();
    calc();
    super.onInit();
  }

  @override
  onClose() {
    _timer.cancel();
    super.onClose();
  }

  calc() {
    _timer = Timer.periodic(Duration(milliseconds: step), (timer) {
      if (state.countDown.value > 1) {
        jump2NextPage();
      }
      state.countDown = state.countDown + stepPrecent;
    });
  }

  void jump2NextPage() {
    _timer.cancel();
    if(_user == null) {
      _jump2LoginPage();
      return;
    }
    jump2HomePage();
  }

  void _jump2LoginPage() {
    Get.offAndToNamed(RouteConfig.login);
  }

  void jump2HomePage() {
    Get.offAndToNamed(RouteConfig.main);
  }

  void _getUserInfo() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    var usr = sp.getString("_user");
    print("user $usr");
    _user = null;
  }
}
